//
//  ICMBalanceUseCouponView.m
//  ICrEAM
//
//  Created by ysw on 2016/11/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMBalanceUseCouponView.h"
#import "ICMBottomBarView.h"
#import "ICMBalanceSelectCouponCell.h"
#import "DeleteCouponAction.h"
#define displayWidth ScreenWidth-ActualWidth(30)*2

@interface ICMBalanceUseCouponView () <UITableViewDelegate,UITableViewDataSource,ICMBottomBarViewDelegate,ICMBalanceSelectCouponCellDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView *couponTableView;
@property (nonatomic, strong) UIView *mainDisplayView;
@property (nonatomic, strong) UIButton *allSelectButton; //全选按钮


@end

@implementation ICMBalanceUseCouponView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = BackgroundColor_Tanslucent_black;
        UITapGestureRecognizer *backgroundGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeView)];
        
        backgroundGesture.delegate = self;
        
        [self addGestureRecognizer:backgroundGesture];
        
        UIView *mainDisplayView = [[UIView alloc] initWithFrame:CGRectMake(ActualWidth(30), ActualHeight(100), displayWidth, ActualHeight(550))];
        mainDisplayView.backgroundColor = [UIColor whiteColor];
        BorderColor(mainDisplayView, BorderColor_Gray_Hex);
        BorderWidth(mainDisplayView, 1.0);
        [self addSubview:mainDisplayView];
        self.mainDisplayView = mainDisplayView;
        
        //头部
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, displayWidth, ActualHeight(70))];
        [mainDisplayView addSubview:titleView];
        
        NSDictionary *titleDic = @{@"font":BoldNaviFont,@"color":TitleColor};
        UILabel *titleLabel = [self createLabelWithDic:titleDic text:@"优惠券抵扣" frame:CGRectMake(0, ActualHeight(25), displayWidth, ActualHeight(25))];
        [titleView addSubview:titleLabel];
        [titleLabel sizeToFit];
        titleLabel.center = CGPointMake(ScreenWidth/2, ActualHeight(70)/2);
        
        UIView *horSep1 = [[UIView alloc]initWithFrame:CGRectMake(0, ActualHeight(70)-1, displayWidth, ActualHeight(1))];
        horSep1.backgroundColor = SepColor_gray;
        [titleView addSubview:horSep1];
        
        //表格部分
        UIView *tableView = [[UIView alloc] initWithFrame:CGRectMake(0, titleView.bottomEdge, displayWidth, ActualHeight(75)+ActualHeight(30)*10)];
        [mainDisplayView addSubview:tableView];
        [tableView addSubview:[self setupTableHeaderView]];
        UITableView *couponTableView = [[UITableView alloc]initWithFrame:CGRectMake(ActualWidth(20), ActualHeight(50), displayWidth-ActualWidth(20)*2, ActualHeight(30)*10)];
        couponTableView.delegate = self;
        couponTableView.dataSource = self;
        couponTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        couponTableView.bounces = NO;
        [couponTableView registerClass:[ICMBalanceSelectCouponCell class] forCellReuseIdentifier:@"CouponCell"];
        [tableView addSubview:couponTableView];
        self.couponTableView = couponTableView;
        
        //全选
        UIButton *allSelectButton = [[UIButton alloc]initWithFrame:CGRectMake(ActualWidth(20), tableView.bottomEdge-ActualHeight(5), 70, 30)];
        [allSelectButton setImage:[UIImage imageNamed:@"jiesuan_xz21"] forState:UIControlStateNormal];
        [allSelectButton setImage:[UIImage imageNamed:Appointment_ActivityChoose] forState:UIControlStateSelected];
        [allSelectButton setTitle:@"全选" forState:UIControlStateNormal];
        allSelectButton.titleLabel.font = TitleFont;
        [allSelectButton setTitleColor:ContentTextColor_Black forState:UIControlStateNormal];
        [allSelectButton addTarget:self action:@selector(clickAllSelectButton:) forControlEvents:UIControlEventTouchUpInside];
        allSelectButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 40);
        allSelectButton.titleEdgeInsets = UIEdgeInsetsMake(0, -35, 0, 0);
        [mainDisplayView addSubview:allSelectButton];
        self.allSelectButton = allSelectButton;
        
        //按钮
        ICMBottomBarView *bottomBarView = [ICMBottomBarView createBottomBarViewWithTitles:@[@"确定"] normalImages:@[[UIImage imageNamed:@"btn_save"]] seletedImages:nil andFrame:CGRectMake(0, ActualHeight(550)-70, displayWidth, 70)];
        bottomBarView.delegate = self;
        [mainDisplayView addSubview:bottomBarView];
        
    }
    return self;
}

- (UIView *)setupTableHeaderView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(ActualWidth(20), ActualHeight(25), displayWidth-ActualWidth(20)*2, ActualHeight(30))];
    headView.backgroundColor = TitleColor;
    
    NSDictionary *headDic = @{@"font":NaviFont,@"color":ContentTextColor_Black};
    UILabel *operateLabel = [self createLabelWithDic:headDic text:@"选择" frame:CGRectMake(0, ActualHeight(7), ActualWidth(50), ActualHeight(15))];
    [headView addSubview:operateLabel];
    
    UIView *firstSep = [[UIView alloc] initWithFrame:CGRectMake(operateLabel.rightEdge, 0, 1, headView.height)];
    firstSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:firstSep];
    
    UILabel *orderLabel = [self createLabelWithDic:headDic text:@"序号" frame:CGRectMake(firstSep.rightEdge, operateLabel.y, ActualWidth(50), ActualHeight(15))];
    [headView addSubview:orderLabel];
    
    UIView *secondSep = [[UIView alloc] initWithFrame:CGRectMake(orderLabel.rightEdge, 0, 1, headView.height)];
    secondSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:secondSep];
    
    UILabel *userNameLabel = [self createLabelWithDic:headDic text:@"客户名称" frame:CGRectMake(secondSep.rightEdge, operateLabel.y, ActualWidth(130), ActualHeight(15))];
    [headView addSubview:userNameLabel];
    
    UIView *thirdSep = [[UIView alloc] initWithFrame:CGRectMake(userNameLabel.rightEdge, 0, 1, headView.height)];
    thirdSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:thirdSep];
    
    UILabel *couponTypeLabel = [self createLabelWithDic:headDic text:@"优惠券类型" frame:CGRectMake(thirdSep.rightEdge, operateLabel.y, ActualWidth(120), ActualHeight(15))];
    [headView addSubview:couponTypeLabel];
    
    UIView *fourthSep = [[UIView alloc] initWithFrame:CGRectMake(couponTypeLabel.rightEdge, 0, 1, headView.height)];
    fourthSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:fourthSep];
    
    UILabel *couponPriceLabel = [self createLabelWithDic:headDic text:@"优惠券金额" frame:CGRectMake(fourthSep.rightEdge, operateLabel.y, ActualWidth(120), ActualHeight(15))];
    [headView addSubview:couponPriceLabel];
    
    UIView *fifthSep = [[UIView alloc] initWithFrame:CGRectMake(couponPriceLabel.rightEdge, 0, 1, headView.height)];
    fifthSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:fifthSep];
    
    UILabel *quantityLabel = [self createLabelWithDic:headDic text:@"优惠券数量" frame:CGRectMake(fifthSep.rightEdge, operateLabel.y, ActualWidth(120), ActualHeight(15))];
    [headView addSubview:quantityLabel];
    
    UIView *sixthSep = [[UIView alloc] initWithFrame:CGRectMake(quantityLabel.rightEdge, 0, 1, headView.height)];
    sixthSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:sixthSep];
    
    UILabel *usedQuantityLabel = [self createLabelWithDic:headDic text:@"已使用数量" frame:CGRectMake(sixthSep.rightEdge, operateLabel.y, ActualWidth(120), ActualHeight(15))];
    [headView addSubview:usedQuantityLabel];
    
    UIView *seventhSep = [[UIView alloc] initWithFrame:CGRectMake(usedQuantityLabel.rightEdge, 0, 1, headView.height)];
    seventhSep.backgroundColor = BorderColor_Gray;
    [headView addSubview:seventhSep];
    
    UILabel *timeLabel = [self createLabelWithDic:headDic text:@"赠送时间" frame:CGRectMake(seventhSep.rightEdge, operateLabel.y, headView.width-usedQuantityLabel.rightEdge, ActualHeight(15))];
    [headView addSubview:timeLabel];
    
    return headView;
}


- (UILabel *)createLabelWithDic:(NSDictionary *)dic text:(NSString *)text frame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = dic[@"font"];
    label.textColor = dic[@"color"];
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

//移除视图
- (void)removeView {
    [self removeFromSuperview];
}

#pragma mark -- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICMBalanceSelectCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CouponCell"];
    if (cell == nil) {
        cell = [[ICMBalanceSelectCouponCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CouponCell"];
    }
    cell.delegate = self;
    cell.indexPath = indexPath;
    if (self.dataArray.count == self.selectedDataArray.count) {
        [cell creatCellWithModel:self.dataArray[indexPath.row] isAll:YES];
    }else{
        [cell creatCellWithModel:self.dataArray[indexPath.row] isAll:NO];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ActualHeight(30);
}
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMBalanceCouponModel *couponModel=self.dataArray[indexPath.row];
    if ([couponModel.USED_QUANTITY doubleValue]>0) {
        [MBProgressHUD showMessage:@"优惠券已使用"];
    }else{
        DeleteCouponAction *action=[[DeleteCouponAction alloc]init];
        action.couponId=couponModel.ITEM_ID;
        [action startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
            [MBProgressHUD showSuccess:@"优惠券删除成功"];
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.couponTableView reloadData];
            
        } failure:^(__kindof YTKBaseRequest *request) {
            
        }];
    }
}

#pragma mark -- ICMBottomBarViewDelegate
- (void)bottomBarViewDidSelectIndex:(NSInteger)index {
    //确定
    double labourUval = 0;
    double partUval = 0;
    for(int i = 0;i<self.selectedDataArray.count;i++)
    {
        ICMBalanceCouponModel *model = self.selectedDataArray[i];
        //工时优惠券
        if([model.COUPON_TYPE isEqualToString:ICMEnumIntToString(ICMEnumCouponTypeLabour)])
        {
            labourUval = labourUval + [model.COUPON_UVAL doubleValue];
            double labourRealPrice = [self.labourRealPrice doubleValue];
            if (labourUval >= labourRealPrice) {
                [self showString:@"工时优惠券应小于实收工时费" forSeconds:1.5];
                return;
            }
        }
        //材料优惠券
        if([model.COUPON_TYPE isEqualToString:ICMEnumIntToString(ICMEnumCouponTypePart)])
        {
            partUval = partUval + [model.COUPON_UVAL doubleValue];
            double partRealPrice = [self.partRealPrice doubleValue];
            if (partUval >= partRealPrice) {
                [self showString:@"材料优惠券应小于实收材料费" forSeconds:1.5];
                return;
            }
        }
    }
    [self removeFromSuperview];
    
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CalculateUseCoupon" object:self userInfo:@{@"LabourUval":[NSString stringWithFormat:@"%.2f",labourUval],@"PartUval":[NSString stringWithFormat:@"%.2f",partUval]}];
}

- (void)clickAllSelectButton:(UIButton *)sender
{
    if (self.dataArray.count > 0) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            for (ICMBalanceCouponModel *model in self.dataArray) {
                model.isSelected = YES;
                [self.selectedDataArray removeAllObjects];
                [self.selectedDataArray addObjectsFromArray:self.dataArray];
            }
        } else {
            for (ICMBalanceCouponModel *model in self.dataArray) {
                model.isSelected = NO;
                [self.selectedDataArray removeAllObjects];
            }
        }
        [self.couponTableView reloadData];
    }
}

- (NSMutableArray *)dataArray
{
    if(!_dataArray)
    {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray *)selectedDataArray
{
    if(!_selectedDataArray)
    {
        _selectedDataArray = [[NSMutableArray alloc] init];
    }
    return _selectedDataArray;
}


- (void)refreshView{
    [self.couponTableView reloadData];
}

//ICMBalanceSelectCouponCellDelegate
- (void)clickedOperationBtnWithIsSelected:(BOOL)isSelected AtIndex:(NSIndexPath *)indexPath
{
    if(isSelected)
    {
        [self.selectedDataArray addObject:self.dataArray[indexPath.row]];
    }
    else
    {
        [self.selectedDataArray removeObject:self.dataArray[indexPath.row]];
    }
    
    if(self.selectedDataArray.count == self.dataArray.count)
    {
        self.allSelectButton.selected = YES;
    }
    else
    {
        self.allSelectButton.selected = NO;
    }
    [self.couponTableView reloadData];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isDescendantOfView:self.mainDisplayView]) {
        return NO;
    }
    return YES;
}


@end
